<!-- 栏目管理 - 栏目关联商品列表  -->
<template>
  <!-- 搜索工作栏 -->
<ContentWrap v-if="productListShow">
  <el-row>
      <el-col :span="22">
        <el-descriptions ref="columnConfigRef" title="配置信息">
          <el-descriptions-item label="栏目名称：">{{columnData.title}}</el-descriptions-item>
          <el-descriptions-item label="图标：">
            <div class="flex" v-if="columnData.icon && columnData.icon != ''">
              <el-image
                fit="cover"
                :src="columnData.icon"
                class="flex-none w-50px h-50px"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="类型：">
            <span v-if="columnData.type == 'wx' || columnData.type === 'WX'">微信端</span>
            <span v-else>移动端</span>
          </el-descriptions-item>
          <el-descriptions-item label="关联商品数量：">{{columnData.productNum}}</el-descriptions-item>
          <el-descriptions-item label="备注：">
            {{columnData.remark}}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col :span="2">
        <el-button              
              link
              type="primary"
              @click="goBack"
            >
              返回
            </el-button>
      </el-col>
  </el-row>
</ContentWrap>

<!-- 列表 -->
<ContentWrap v-if="productListShow">
  <el-row>
    <el-col :span="24">
      <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            class="!w-240px"
            clearable
            placeholder="请输入商品名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
          <el-button
            v-hasPermi="['infra:column:productAdd']"
            plain
            type="primary"
            @click="openAddProductForm(columnData.id, 'create')"
          >
            <Icon class="mr-5px" icon="ep:plus" />
            新增
          </el-button>     
        </el-form-item>
      </el-form>
    </el-col>
  </el-row> 
  <el-row>
    <el-col :span="24">
      <el-table v-loading="loading" :data="list">
        <el-table-column label="ID" min-width="140" prop="id" />
        <el-table-column label="商品图" min-width="120">
          <template #default="{ row }">
            <div class="flex">
              <el-image
                fit="cover"
                :src="row.productImage"
                class="flex-none w-50px h-50px"
                @click="imagePreview(row.productImage)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品名称" min-width="240" prop="productName" />
        <el-table-column align="center" label="售价" min-width="100" prop="salePrice" >
          <template #default="{row}">{{floatToFixed2(row.salePrice)}}</template>
        </el-table-column>      
        <el-table-column align="center" label="支付价" min-width="100" prop="payPrice" />
        <el-table-column align="center" label="排序" min-width="80" prop="sort" />
        <el-table-column align="center" label="是否活动" min-width="90">
          <template #default="{ row }">
            <el-switch
              v-model="row.activity"
              :active-value="0"
              :inactive-value="1"
              active-text="是"
              inactive-text="否" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="活动类型" min-width="100" prop="activityType">
          <template #default="{ row }">
            <div v-if="row.activityType && row.activityType != ''">
              <dict-tag :type="DICT_TYPE.MALL_COLUMN_ACTIVTY_TYPE" :value="row.activityType" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :formatter="dateFormatter"
          align="center"
          label="添加时间"
          prop="createTime"
          width="180"
        />
        <el-table-column align="center" fixed="right" label="操作" min-width="200">
          <template #default="{ row }">
            <el-button
              v-hasPermi="['infra:column:productUpdate']"
              link
              type="primary"
              @click="openEditForm(row)"
            >
              修改
            </el-button>
            <el-button
                v-hasPermi="['infra:column:productDelete']"
                link
                type="danger"
                @click="handleDelete(row.id)"
              >
                删除
            </el-button>              
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </el-col>    
  </el-row> 
</ContentWrap>
<Dialog title="编辑商品信息" v-model="editFormShow" :close-on-click-modal="false">
    <el-form
      ref="editProductFormRef"
      :model="ediProductFormData"
      :rules="editProductFormRules"
      label-width="80px"
    >
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="ediProductFormData.productName" placeholder="商品名称不能为空" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="ediProductFormData.sort" controls-position="right" :min="0" />
      </el-form-item>      
    </el-form>
    <template #footer>
      <el-button @click="submitFormHandle" type="primary" :disabled="EditformLoading">确 定</el-button>
      <el-button @click="closeEditform">取 消</el-button>
    </template>
  </Dialog>
<addProductForm ref="addProductFormRef" :columnId="columnId" @cancel-form-handle="cancelFormHandle"/>
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import * as MallColumnApi from '@/api/mall/plate/column'
import addProductForm from './addProductForm.vue'
import { floatToFixed2 } from '@/utils'
import { column } from 'element-plus/es/components/table-v2/src/common'

defineOptions({ name: 'ColumnConfig' })
const props = defineProps({columnId: {type: Number}})

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const loading = ref(false) // 列表的加载中
const productListShow = ref(true) // 列表or表单
const showAddProductForm = ref(false)
const exportLoading = ref(false) // 导出的加载中
const editFormShow = ref(false) //商品编辑表单
const total = ref(0) // 列表的总页数
const list = ref<MallColumnApi.ColumnProduct[]>([]) // 列表的数据

const addProductFormRef = ref(null)

const columnConfigRef = ref(null)

const columnData = ref<MallColumnApi.ColumnDetail>({
  id: undefined,
  icon: '',
  title: '',
  type: '',
  sort: 0,
  status: '',
  remark: '',
  productNum: 0
})
const EditformLoading = ref(false)
const ediProductFormData = ref({
  id: undefined,
  name: '',
  productId: undefined,
  columnId: undefined,
  sort: 0
})

const editProductFormRef = ref() // 表单 Ref

const editProductFormRules = reactive({
  productName: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '商品信息有误', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})

const orchardId = ref()

const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  name: '',
  columnId: undefined
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref

const emit = defineEmits(['cancelConfig']) // 定义 success 事件，用于操作成功后的回调

const getList = async () => {
  loading.value = true
  queryParams.value.columnId = props.columnId
  try {
    const data = await MallColumnApi.getProductList(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const openConfig =  async (id) => {
  loading.value = true
  productListShow.value = true
  if(props.columnId != null && props.columnId != undefined) {
    try {
      const data = await MallColumnApi.getColumnDetail({id: props.columnId})
      columnData.value = data
      await getList()
    }
    finally {
      loading.value = false
    }    
  }
}

const handleDelete = async (id) => {  
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    loading.value = true
    await MallColumnApi.deleteColumnProduct({id})
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } finally {
    loading.value = false
  }
}
const goBack = () => {
  emit('cancelConfig')
}

//打开添加商品窗口
const openAddProductForm = (id?: number, type: string) => {
  let row = {columnId: id}
  addProductFormRef.value.open(type, row)
}

const openEditForm = (row) => {
  editFormShow.value = true
  console.log(editFormShow.value)
  ediProductFormData.value = row
}

const submitFormHandle = async () => {
  const valid = await editProductFormRef.value.validate()
  if (!valid) return
  EditformLoading.value = true
  await MallColumnApi.updateColumnProduct(ediProductFormData.value)
  message.success(t('common.updateSuccess'))
  editFormShow.value = false
  EditformLoading.value = false
  await getList()
}

const closeEditform = () => {
  editFormShow.value = false
  ediProductFormData.value = {
      id: undefined,
      name: '',
      productId: undefined,
      columnId: undefined,
      sort: 0
    }
}

const cancelFormHandle = () => {
  productListShow.value = true
  getList()
}

/** 激活时 */
onActivated(() => {

})

/** 初始化 **/
onMounted(async () => {
  loading.value = true
  if(props.columnId != null && props.columnId != undefined) {
    try {
      const data = await MallColumnApi.getColumnDetail({id: props.columnId})
      columnData.value = data
      await getList()
    }
    finally {
      loading.value = false
    }    
  }
})
</script>